﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using SilverlightDesktop.Controls;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
using VAdvantage.Common;
using VAdvantage.DataBase;
using System.Data.SqlClient;
using VAdvantage.SqlExec;
using VAdvantage.Classes;
using VAdvantage.Model;
using VAdvantage.Utility;
using VAdvantage.Logging;
//using System.Drawing.Printing;
using System.Threading;
using System.Collections;


namespace VAdvantage.Framework
{
    /// <summary>
    /// A class to set preference
    /// </summary>
    public partial class UserPreference : Apps.CFrame
    {
        #region PrivateVariable
        /**	Logger*/
        private static VLogger log = VLogger.GetVLogger(typeof(UserPreference).FullName);
        Context ctx = Utility.Envs.GetContext();
        #endregion

        public UserPreference()
            : base(Msg.GetMsg(Envs.GetContext(), "Preference", true))
        //: base(true, false, true, "User Preference")
        {
            base.SetTitle(Msg.GetMsg(Envs.GetContext(), "Preference", true));
            InitializeComponent();
            LayoutRootU.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
            Init(); //loads the text
            //InitialFormSetting.SetFont(this);

        }

        #region Get properties of control
        public bool GetAutoCommit
        {
            get
            {
                if (AutoCommitControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetAccountingTab
        {
            get
            {
                if (ShowAccountingTabControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetAdvancedTab
        {
            get
            {
                if (ShowAdvancedTabControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetTranslationTab
        {
            get
            {
                if (ShowTranslationTabControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetAutoLogin
        {
            get
            {
                if (AutoLoginControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetStorePassword
        {
            get
            {
                if (StorePasswordControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetPreviewPrint
        {
            get
            {
                if (PreviewPrintControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetAutoNewRecord
        {
            get
            {
                if (AutoNewRecordControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetCacheWindows
        {
            get
            {
                if (CahceWindowControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetDictionaryMaintenence
        {
            get
            {
                if (DictionaryMaintenenceControl.IsChecked == true) return true; else return false;
            }
        }
        public bool GetTraceFile
        {
            get
            {
                if (TraceFileControl.IsChecked == true) return true; else return false;
            }
        }

        public string GetPrinterFromCombo
        {
            get
            {
                //return cmbPrinter.Text;
                // return cmbPrinter.GetText();
                return "";


            }

            set
            {
                //cmbPrinter.Text = value;
                // cmbPrinter.SetValue(value);
            }
        }

        public int GetWorkspacePageSize
        {
            get
            {
               return Convert.ToInt32( cmbPageSize.SelectedItem);
            }
            set
            {
                cmbPageSize.SelectedItem = value;
            }
        }

        #endregion

        #region Gets the Installed printers on system
        /// <summary>
        /// Gets the printer in database
        /// </summary>
        private void GetPrinters()
        {
            cmbPrinter.Items.Clear();
            //foreach (String strPrinterName in PrinterSettings.InstalledPrinters)
            //{
            //    cmbPrinter.Items.Add(strPrinterName);
            //}

            if (cmbPrinter.Items.Count > 0)
                cmbPrinter.SelectedIndex = 0;

        }
        #endregion

        private void Save_Preference()
        {
            log.Config("");
            //  UI
            //	AutoCommit
            //Context ctx = Utility.TimeUtil.GetContext();
            m_preference.SetIsAutoCommit((bool)chkAutoCommit.IsChecked);
            ctx.SetAutoCommit((bool)chkAutoCommit.IsChecked);

            Ini.SetProperty(Ini.P_A_NEW, (chkAutoNewRecord.IsChecked).Equals(true) ? "Y" : "N");
            ctx.SetAutoNew((bool)chkAutoNewRecord.IsChecked);

            Ini.SetProperty(Ini.P_TRACEFILE, (chkTraceFile.IsChecked).Equals(true) ? "Y" : "N");
            KeyNamePair kp = (KeyNamePair)cmbTraceLevel.SelectedItem;
            Ini.SetProperty(Ini.P_TRACELEVEL, kp.GetName());

            //Ini.SetProperty(Ini.P_Show_ClientOrg, (chkClientOrg.IsChecked).Equals(true) ? "Y" : "N");
            //ctx.SetShowClientOrg((chkClientOrg.IsChecked).Equals(true) ? "Y" : "N");

            Ini.SetProperty(Ini.CO_SHOWLEVEL, cmbClientOrg.SelectedIndex < 0 ? "0" : cmbClientOrg.SelectedIndex.ToString());
            ctx.SetShowClientOrg(cmbClientOrg.SelectedIndex < 0 ? "0" : cmbClientOrg.SelectedIndex.ToString());

            Ini.SetProperty(Ini.W_PAGESIZE, cmbPageSize.SelectedItem.ToString());
            ctx.SetWorkSpacePageSize(cmbPageSize.SelectedItem.ToString());

            Ini.SetProperty(Ini.P_Show_Mini_Grid, (chkShowMiniGrid.IsChecked).Equals(true) ? "Y" : "N");
            ctx.SetShowMiniGrid((chkShowMiniGrid.IsChecked).Equals(true) ? "Y" : "N");

            //	AutoLogin
            Ini.SetProperty(Ini.P_A_LOGIN, (chkAutoLogin.IsChecked).Equals(true) ? "Y" : "N");
            //	Save Password
            Ini.SetProperty(Ini.P_STORE_PWD, (chkStorePassword.IsChecked).Equals(true) ? "Y" : "N");
            //	Show Acct Tab
            m_preference.SetIsShowAcct((bool)chkShowAccountingTab.IsChecked);
            ctx.SetContext("#ShowAcct", ((bool)chkShowAccountingTab.IsChecked));
            //	Show Trl Tab
            m_preference.SetIsShowTrl((bool)chkShowTranslationTab.IsChecked);
            ctx.SetContext("#ShowTrl", ((bool)chkShowTranslationTab.IsChecked));
            //	Show Advanced Tab
            m_preference.SetIsShowAdvanced((bool)chkShowAdvancedTab.IsChecked);
            ctx.SetContext("#ShowAdvanced", ((bool)chkShowAdvancedTab.IsChecked));

            ////  ConnectionProfile
            //ValueNamePair ppNew = (ValueNamePair)connectionProfile.getSelectedItem();
            //String cpNew = ppNew.getValue();
            //String cpOld = CConnection.get().getConnectionProfile();
            //CConnection.get().setConnectionProfile(cpNew);
            //if (!cpNew.equals(cpOld)
            //    && (cpNew.equals(CConnection.PROFILE_WAN) || cpOld.equals(CConnection.PROFILE_WAN)))
            //    ADialog.info(0, this, "ConnectionProfileChange");

            Ini.SetProperty(Ini.P_CACHE_WINDOW, (chkCacheWindows.IsChecked.Equals(true) ? "Y" : "N"));

            //  Print Preview
            Ini.SetProperty(Ini.P_PRINTPREVIEW, (chkPreviewPrint.IsChecked).Equals(true) ? "Y" : "N");

            //	TraceLevel/File
            //KeyNamePair kn = (KeyNamePair)cmbTraceLevel.SelectedItem;
            //Level level = kn.GetName();
            //VLogMgt.SetLevel(level);

            Ini.SetProperty(Ini.P_TRACEFILE, chkTraceFile.IsChecked.Equals(true) ? "Y" : "N");
            //  Printer
            //String printer = cmbPrinter.Text;
            //Silverlight //String printer = cmbPrinter.SelectedItem.ToString();
            //Silverlight //ctx.SetPrinterName(printer);
            //Silverlight //m_preference.SetPrinterName(printer);
            //  Date (remove seconds)
            //DateTime ts = dtDate.Value;

            //if (ts != null)
            //    ctx.SetContext("#Date", ts);

            Ini.SaveProperties(Ini.IsClient());

            ThreadPool.QueueUserWorkItem(delegate
            {
                m_preference.Save();
                Dispatcher.BeginInvoke(delegate
                {
                    btnOk.IsEnabled = true;
                });
            });

            this.Close();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("pending..");
            //return;
            btnOk.IsEnabled = false;
            Save_Preference();
        }

        #region Control Properties
        private CheckBox AutoCommitControl
        {
            get
            {
                return chkAutoCommit;
            }
        }

        private CheckBox AutoLoginControl
        {
            get
            {
                return chkAutoLogin;
            }
        }

        private CheckBox ShowAccountingTabControl
        {
            get
            {
                return chkShowAccountingTab;
            }
        }


        private CheckBox ShowAdvancedTabControl
        {
            get
            {
                return chkShowAdvancedTab;
            }
        }


        private CheckBox ShowTranslationTabControl
        {
            get
            {
                return chkShowTranslationTab;
            }
        }

        private CheckBox StorePasswordControl
        {
            get
            {
                return chkStorePassword;
            }
        }

        private CheckBox AutoNewRecordControl
        {
            get
            {
                return chkAutoNewRecord;
            }
        }

        private CheckBox CahceWindowControl
        {
            get
            {
                return chkCacheWindows;
            }
        }

        private CheckBox PreviewPrintControl
        {
            get
            {
                return chkPreviewPrint;
            }
        }

        private ComboBox PrinterControl
        {
            get
            {
                return cmbPrinter;
            }
        }

        private CheckBox DictionaryMaintenenceControl
        {
            get
            {
                return chkDictionaryMaintain;
            }
        }

        private CheckBox TraceFileControl
        {
            get
            {
                return chkTraceFile;
            }
        }

        private ListBox ListBoxControl
        {
            get
            {
                return lstContext;
            }
        }

        #endregion

        private void UserPreference_Load(object sender, RoutedEventArgs e)
        {

            LoadMe();
            StringBuilder sta = new StringBuilder("#");
            sta.Append(Utility.Envs.GetContext().Size()).Append(" - ")
                .Append(Utility.Msg.Translate(Utility.Envs.GetContext(), "AD_Window_ID"));
            // .Append("=");

            SetStatusMsg(sta.ToString());//Uncomment it

            txtConnectionDetail.Text = GetProfileInfo();

            vchkErrorOnly.IsChecked = true;
            // set grid properties
            //CommonFunctions.SetDataGridPrperties(vdgvError);//Uncomment it
            // vdgvError.IsReadOnly = true;//for silverlight
        }

        // Executes when the user navigates to this page.
        /// <summary>
        /// 
        /// </summary>
        private void Init()
        {
            chkAutoCommit.Content = Msg.GetMsg(Envs.GetContext(), "AutoCommit", true);
            chkAutoLogin.Content = Msg.GetMsg(Envs.GetContext(), "AutoLogin", true);
            chkAutoNewRecord.Content = Msg.GetMsg(Envs.GetContext(), "AutoNew", true);
            chkCacheWindows.Content = Msg.GetMsg(Envs.GetContext(), "CacheWindow", true);
            chkDictionaryMaintain.Content = Msg.GetMsg(Envs.GetContext(), "ViennaSys", true);
            chkPreviewPrint.Content = Msg.GetMsg(Envs.GetContext(), "AlwaysPrintPreview", true);
            chkShowAccountingTab.Content = Msg.GetMsg(Envs.GetContext(), "ShowAcctTab", true);
            chkShowAdvancedTab.Content = Msg.GetMsg(Envs.GetContext(), "ShowAdvancedTab", true);
            chkShowTranslationTab.Content = Msg.GetMsg(Envs.GetContext(), "ShowTranslationTab", true);
            chkStorePassword.Content = Msg.GetMsg(Envs.GetContext(), "StorePassword", true);
            chkTraceFile.Content = Msg.GetMsg(Envs.GetContext(), "TraceFile", true);
            cmdRole.Content = Msg.GetMsg(Envs.GetContext(), "Role", true);
            lblTraceLevel.Content = Msg.GetMsg(Envs.GetContext(), "TraceLevel", true);
            vlblDateText.Content = Msg.GetMsg(Envs.GetContext(), "Date", true);
            vlblPrinterText.Content = Msg.GetMsg(Envs.GetContext(), "Printer", true);
            vlblClientOrg.Content = Msg.GetMsg(Envs.GetContext(), "Show", true);
            vlblPageSize.Content = Msg.GetMsg(Envs.GetContext(), "PageSize", true);

            KeyNamePair[] kp = Level.GetLevels();
            KeyNamePair iniValue = null;
            for (int i = 0; i <= kp.Length - 1; i++)
            {
                cmbTraceLevel.Items.Add(kp[i]);
                if (kp[i].GetName().Equals(Ini.GetProperty(Ini.P_TRACELEVEL)))
                    iniValue = kp[i];
                //if (kp[i].GetName().Equals("ALL"))
                //    iniValue = kp[i]; 
            }

            cmbTraceLevel.SelectedItem = iniValue;

            cmbClientOrg.ItemsSource = Envs.GetCOShowLevel();

            int index = Convert.ToInt32(Ini.GetProperty(Ini.CO_SHOWLEVEL));

            cmbClientOrg.SelectedIndex = index;

            cmbPageSize.ItemsSource = Envs.GetWorkSpacePageSize();
            int pageNo = Convert.ToInt32(Ini.GetProperty(Ini.W_PAGESIZE));
            cmbPageSize.SelectedItem = pageNo;


        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Gets the profile info
        /// </summary>
        /// <returns>return profile info as string</returns>
        private string GetProfileInfo()
        {
            StringBuilder strProfile = new StringBuilder("");
            // strProfile.Append(Ini.CreateConnectionString());//Uncoment line

            return strProfile.ToString();
        }

        /// <summary>
        /// Get the context values
        /// </summary>
        private void GetContextValues()
        {
            Context ctx = Utility.Envs.GetContext();

            String[] context = ctx.GetEntireContext();

            //for (int i = 0; i < ctx.GetSortedList().Count - 1; i++)
            //{
            //    lstContext.Items.Add(ctx.GetSortedList().Keys[i].ToString() + " == " + ctx.GetSortedList().Values[i].ToString());
            //}
            //while (en.MoveNext())
            //{
            //    lstContext.it
            //lstContext.Items.Add(ctx.GetSortedList().Keys[i].ToString() + " == " + ctx.GetSortedList().Values[i].ToString());


            //lstContext.Items.AddRange(context);
            lstContext.ItemsSource = context;

            //}
        }

        private void lstContext_SelectedIndexChanged(object sender, SelectionChangedEventArgs e)
        {
            //string rep = lstContext.Text.Replace("==", "=");
            //string[] var = rep.Split('=');
            //lblVariableName.Text = var[0].ToString();
            //lblVariableValue.Text = var[1].ToString();

            String value = (String)lstContext.SelectedValue;
            if (value == null)
                return;
            int pos = value.IndexOf("==");
            if (pos == -1)
            {
                lblVariableName.Text = "";
                lblVariableValue.Text = value;
            }
            else
            {
                lblVariableName.Text = value.Substring(0, pos).Replace('|', '\n');
                lblVariableValue.Text = value.Substring(pos + 3);
            }

        }

        #region "Errors Tab"


        private void vchkErrorOnly_CheckedChanged(object sender, RoutedEventArgs e)
        {
            // bind the grid
            DisplayErrors();

        }

        private void vbtnReset_Click(object sender, RoutedEventArgs e)
        {
            VLogErrorBuffer.Get(true).ResetBuffer((bool)vchkErrorOnly.IsChecked);
            DisplayErrors();

        }

        /// <summary>
        /// Binds the log grid
        /// </summary>
        /// <author>Veena Pandey</author>
        private void BindGrid()
        {
            // set datasource of the grid
            vdgvError.ItemsSource = (ErrorLog.GetErrorLog((bool)vchkErrorOnly.IsChecked)).GetBindableData(new Connector());//Uncoment Line
            // set tab text
            if (vchkErrorOnly.IsChecked == true)
            {
                tabError.Content = Msg.GetMsg(Envs.GetContext(), "Errors", true);
            }
            else
            {
                tabError.Content = Msg.GetMsg(Envs.GetContext(), "TraceInfo", true);
            }
            // set tab header text with total count
            tabError.Content = tabError.Content + " (" + ErrorLog.GetTotRecords() + ")";
        }

        // opens Email window to send mail
        private void vbtnSentMail_Click(object sender, RoutedEventArgs e)
        {
            // get full content to be send in mail
            string content = GetDetailContent() + ErrorLog.ErrorFileContent((bool)vchkErrorOnly.IsChecked);
            // opens Email window with content
            // EMailDialog email = new VAdvantage.Framework.EMailDialog(VAdvantage.Model.MUser.Get(Envs.GetContext()), "EMail Trace", "", "Vienna Trace Info", VLogErrorBuffer.Get(true).GetErrorInfo(Envs.GetContext(), vchkErrorOnly.IsChecked));//uncoment line
            //FixedWinTemp objEmail = new FixedWinTemp("", "", content);
            //email.Show();//uncoment line
        }

        //Saves log to a file
        private void vbtnSaveToFile_Click(object sender, RoutedEventArgs e)
        {
            //Open SaveFileDialog window
            SaveFileDialog objSave = new SaveFileDialog();
            // set filter of the window
            objSave.Filter = "All files (*.*)|*.*";
            // set default name of the file to be created

            //string fileName = "TraceLog.txt";//property not found
            //objSave.Name = fileName;//property not found

            // set default extension of the file
            objSave.DefaultExt = "txt";
            // if user clicks on "OK" button
            //bool? result = false;// objSave.ShowDialog();//silverlight
            //if (result == true) //if (objSave.ShowDialog() == DialogResult.OK)
            //  objSave.ShowDialog();//silverlight
            if (objSave.ShowDialog() == true)
            {
                string fileExt = "";
                // get fullfile name entered by the user in save dialog window
                string[] finalSplit = objSave.SafeFileName.Trim().Split('.');
                if (finalSplit.Length > 1)
                {
                    // get the file extension in case user has selected another file format
                    fileExt = finalSplit[finalSplit.Length - 1];
                }
                //set extension of the file
                objSave.DefaultExt = fileExt;
                if (fileExt == "txt" || fileExt == "doc" || fileExt == "xls" || fileExt == "rtf")
                {
                    //saves log to a file
                    ///  ErrorLog.SaveLogToFile(objSave, (bool)vchkErrorOnly.IsChecked, GetDetailContent());
                    StringBuilder content = new StringBuilder();
                    IList rowSource = vdgvError.ItemsSource as IList;
                    if (rowSource != null)
                    {
                        for (int i = 0; i < rowSource.Count; i++)
                        {
                            content.Append("-------------------------------\r\n");
                            for (int j = 0; j < vdgvError.Columns.Count; j++)
                            {
                                content.Append(((BindableObject)rowSource[i]).GetValue(j).ToString() + " :");
                            }
                        }
                    }



                    System.IO.StreamWriter writer = new System.IO.StreamWriter(objSave.OpenFile());
                    // write the extra content into stream
                    writer.Write(GetDetailContent() + "\r\n");
                    // get log content and writes into stream
                    writer.Write(content);
                    //close the stream
                    writer.Close();

                }
            }
        }

        /// <summary>
        /// Get content of first and second tab
        /// </summary>
        /// <returns>string content of first and second tab</returns>
        /// <author>Veena Pandey</author>
        private string GetDetailContent()
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(txtConnectionDetail.Text.Trim() + "\r\n");

            int totCount = lstContext.Items.Count;
            string contentText = Msg.GetMsg(Envs.GetContext(), "Context", true);
            for (int i = 0; i < totCount; i++)
            {
                if (i == 0)
                {
                    sql.Append("=== " + contentText + " ===\r\n");
                }
                sql.Append(lstContext.Items[i].ToString() + "\r\n");
            }
            return sql.ToString();
        }

        #endregion

        /** User Preference		*/
        private MUserPreference m_preference = null;
        MRole objMrol = null;
        private void SetValuePref()
        {
            if (objMrol.IsShowAcct())
                chkShowAccountingTab.IsChecked = m_preference.IsShowAcct();
            else
            {
                chkShowAccountingTab.IsChecked = false;
                chkShowAccountingTab.IsEnabled = false;
            }

            //	Show Trl/Advanced Tab
            chkShowTranslationTab.IsChecked = m_preference.IsShowTrl();
            chkShowAdvancedTab.IsChecked = m_preference.IsShowAdvanced();
        }

        private void LoadMe()
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                MUser user = MUser.Get(Utility.Envs.GetContext());
                m_preference = user.GetPreference();
                objMrol = MRole.GetDefault();
                Deployment.Current.Dispatcher.BeginInvoke
            (SetValuePref);
            });


            chkAutoCommit.IsChecked = Utility.Envs.GetContext().IsAutoCommit();
            chkAutoNewRecord.IsChecked = Utility.Envs.GetContext().IsAutoNew();
            chkAutoLogin.IsChecked = Ini.IsPropertyBool(Ini.P_A_LOGIN);
            chkStorePassword.IsChecked = Ini.IsPropertyBool(Ini.P_STORE_PWD);

            //SetValuePref()

            //chkClientOrg.IsChecked = Ini.IsShowClientOrg();
            chkShowMiniGrid.IsChecked = Ini.IsShowMiniGrid();

            chkCacheWindows.IsChecked = Ini.IsCacheWindow();
            //  Print Preview
            chkPreviewPrint.IsChecked = Ini.IsPropertyBool(Ini.P_PRINTPREVIEW);
            //	TraceLevel
            chkTraceFile.IsChecked = Ini.IsPropertyBool(Ini.P_TRACEFILE);

            //  Printer
            //cmbPrinter.Text = Utility.TimeUtil.GetContext().GetPrinterName();
            //cmbPrinter.SetValue(Utility.TimeUtil.GetContext().GetPrinterName());//silver light comment
            //  Date

            dtDate.SetValue(null);
            //set date time in siverlight
            dtDate.SetValue(CommonFunctions.CovertMilliToDate(Utility.Envs.GetContext().GetContextAsTime("#Date")));

            //	--	Load and sort Context	--
            String[] context = Utility.Envs.GetContext().GetEntireContext();
            //lstContext.DataSource = context;
            lstContext.ItemsSource = context;
        }

        private void cmdRole_Click(object sender, RoutedEventArgs e)
        {


            String text = "";
            this.Cursor = Cursors.Wait;
            this.IsEnabled = false;
            ThreadPool.QueueUserWorkItem(delegate
            {
                text = MRole.GetDefault().ToStringX(Utility.Envs.GetContext());
                Dispatcher.BeginInvoke(delegate
                {
                    this.Cursor = Cursors.Arrow;
                    this.IsEnabled = true;
                    ShowMessage.Info("RoleInfo", true, text, "");
                });
            });
        }

        private void ErrorReset()
        {
            VLogErrorBuffer.Get(true).ResetBuffer((bool)vchkErrorOnly.IsChecked);
            //cmd_displayErrors();
        }	//	cmd_errorReset

        private void DisplayErrors()
        {
            vdgvError.Columns.Clear();
            vdgvError.ItemsSource = null;
            //List<List<Object>> data = VLogErrorBuffer.Get(true).GetLogData(vchkErrorOnly.IsChecked);
            //List<String> columnNames = VLogErrorBuffer.Get(true).GetColumnNames(Envs.GetContext());
            List<String> errorList = new List<string>();
            /**	Constains column name for Datagrindview binding				*/

            object[] colName = VLogErrorBuffer.Get(true).GetColumnNames(Envs.GetContext());
            /**	Constains Data for Datagrindview binding				*/
            object[,] errorData = VLogErrorBuffer.Get(true).GetLogData((bool)vchkErrorOnly.IsChecked);

            //vdgvError.ItemsSource = errorData;
            //vdgvError.DataSource = new VAdvantage.Print.ArrayDataView(errorData, colName);//Uncoment line
            DataTable dt = new DataTable();
            String colNames = null;

            for (int i = 0; i < colName.Length; i++)
            {
                if (colName[i].ToString().Contains("."))
                {
                    colNames = colName[i].ToString().Substring(0, colName[i].ToString().IndexOf('.'));
                }
                else
                {
                    colNames = colName[i].ToString();
                }
                DataColumn dc = new DataColumn(colNames);
                dt.Columns.Add(dc);
                DataGridTextColumn txtcol = new DataGridTextColumn();
                txtcol.Binding = new System.Windows.Data.Binding(dt.Columns[i].ColumnName);
                txtcol.Header = colName[i].ToString();
                //txtcol.Width = DataGridLength.SizeToCells;
                vdgvError.Columns.Add(txtcol);
            }

            int NoOfErrors = errorData.GetUpperBound(0) + 1;
            //if (errorData.GetUpperBound(0) == -1)
            //{
            //    NoOfErrors = 0;
            //}
            //else
            //{
            //    NoOfErrors = errorData.GetUpperBound(0)+1;
            //}


            if (errorData.Length != 0)
            {
                for (int i = 0; i <= errorData.GetUpperBound(0); i++)
                {
                    DataRow dr = new DataRow(dt);
                    for (int j = 0; j < colName.Length; j++)
                    {
                        if (errorData[i, j] == null)
                        {
                            dr[j] = "";
                        }
                        else
                        {
                            dr[j] = errorData[i, j];
                        }
                    }
                    dt.Rows.Add(dr);
                }


                vdgvError.ItemsSource = dt.GetBindableData(new Connector());
                vdgvError.IsReadOnly = true;
                tabError.Header = tabError.Header + " (" + NoOfErrors.ToString() + ")";
            }

            // set tab text
            if (vchkErrorOnly.IsChecked == true)
            {
                tabError.Header = Msg.GetMsg(Envs.GetContext(), "Errors", true);
                tabError.Header = tabError.Header + " (" + NoOfErrors.ToString() + ")";
            }
            else
            {
                tabError.Header = Msg.GetMsg(Envs.GetContext(), "TraceInfo", true);
                tabError.Header = tabError.Header + " (" + NoOfErrors.ToString() + ")";
            }
            Logger ObjLogger = new Logger("ErrorList");
            errorList = ObjLogger.GetErrors();

            //vdgvError.ItemsSource = errorList;

            // set tab header text with total count
            //tabError.Content = tabError.Content + " (" + vdgvError.Rows.Count + ")";//Uncoment line

        }

        private void CFrame_Loaded(object sender, RoutedEventArgs e)
        {
            LoadMe();
            StringBuilder sta = new StringBuilder("#");
            sta.Append(Utility.Envs.GetContext().Size()).Append(" - ")
                .Append(Utility.Msg.Translate(Utility.Envs.GetContext(), "AD_Window_ID"));
            // .Append("=");

            SetStatusMsg(sta.ToString());//silverlight Uncomment it
            VStatusBar.DataContext = sta;
            txtConnectionDetail.Text = GetProfileInfo();
            vchkErrorOnly.IsChecked = true;
            // set grid properties
            //CommonFunctions.SetDataGridPrperties(vdgvError);//Uncomment it
            //vdgvError.IsReadOnly = true; for silverlight
        }

        private void SetStatusMsg(string msg)
        {
            VStatusBar.SetStatusLine(msg);
        }

        private void vchkErrorOnly_Unchecked(object sender, RoutedEventArgs e)
        {

        }
    }
}
